package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    @Override
    public void save(Category category) {
        category.setId(IdUtil.getSnowflake(1,1).nextId());
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
//        category.setCreateUser(1L);
//        category.setUpdateUser(1L);
        categoryMapper.save(category);
    }

    @Override
    public void update(Category category) {
//        category.setUpdateUser(1L);
//        category.setUpdateTime(new Date());
        categoryMapper.update(category);
    }

    @Override
//    public ResultInfo delete(Long id) {
//        Integer num1=categoryMapper.countDishByCategoryById(id);
//        if (num1>0){
//            return ResultInfo.error("下面有菜品，不能删除");
//        }
//        Integer num2=categoryMapper.countSetmealByCategoryById(id);
//        if (num2>0){
//            return ResultInfo.error("下面有菜品，不能删除");
//        }
//        categoryMapper.delete(id);
//        return ResultInfo.success(null);
//    }
    public void delete(Long id) {
        Integer num1=categoryMapper.countDishByCategoryById(id);
        if (num1>0){
            throw  new CustomException("当前分类下有菜品，不能的删除");
        }
        Integer num2=categoryMapper.countSetmealByCategoryById(id);
        if (num2>0){
            throw  new CustomException("当前分类下有菜品，不能的删除");
        }
        categoryMapper.delete(id);
        //return ResultInfo.success(null);
    }

    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);
        return categoryMapper.selectList(wrapper);
    }
}
